package com.example.trabajofinal.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.example.trabajofinal.R;
import com.example.trabajofinal.adapter.CursosAdapter;
import com.example.trabajofinal.backend.CursosManager;
import com.example.trabajofinal.model.Curso;

public class CursosActivity extends CommonActivity
{
	private CursosAdapter adapter;
	private ProgressBar mProgressBar = null;
	private ListView mListView = null;
	//private ArrayList<Curso> mCursos;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cursos_activity);

		mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);

		new BajarCursos().execute();
	}


	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.getItem(0).setEnabled(false); //Cursos
		menu.getItem(1).setEnabled(true); // Mis Cursos
		menu.getItem(2).setEnabled(true); // Mapa
		return super.onPrepareOptionsMenu(menu);
	}


	class BajarCursos extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {

			if(CursosManager.getInstance().getCursos() == null){
				CursosManager.getInstance().downloadCursos();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			adapter = new CursosAdapter(CursosActivity.this, CursosManager.getInstance().getCursos());

			mListView = (ListView) findViewById(R.id.cursosList);
			mListView.setAdapter(adapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					Curso curso = (Curso) adapter.getItem(position);
					Log.d("Curso", curso.getTitulo());

					Intent i = new Intent(CursosActivity.this, DetalleActivity.class);
					i.putExtra("curso", curso);
					CursosActivity.this.startActivity(i);

				}
			});

			mProgressBar.setVisibility(View.GONE);
		}

	}

}
